package com.catazy.wanandroid.ndkdemo

import android.content.Context
import android.opengl.GLSurfaceView
import android.util.AttributeSet
import android.util.Log
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10

/**
 * 作者: Tao
 * 日期: 2024/4/25
 * 时间: 14:51
 * 描述:
 */
class MyGLSurfaceView(context: Context, attrs: AttributeSet? = null) :
    GLSurfaceView(context, attrs) {

    companion object {
        private const val TAG = "MyGLSurfaceView"

        // 图像格式 RGBA
        const val IMAGE_FORMAT_RGBA = 0x01
        // 图像格式 NV21
        const val IMAGE_FORMAT_NV21 = 0x02
        // 图像格式 NV12
        const val IMAGE_FORMAT_NV12 = 0x03
        // 图像格式 I420
        const val IMAGE_FORMAT_I420 = 0x04
    }

    private var mRenderer: MyGLRenderer
    private var mNativeRender: MyNativeRender

    init {
        // 创建 OpenGL ES 3.0 上下文
        setEGLContextClientVersion(3)
        mNativeRender = MyNativeRender()
        mRenderer = MyGLRenderer(mNativeRender)
        // 设置用于在 GLSurfaceView 上绘图的渲染器
        setRenderer(mRenderer)
        // 设置渲染模式
        // RENDERMODE_WHEN_DIRTY 表示只有在调用 requestRender() 时才绘制视图
        // RENDERMODE_CONTINUOUSLY 表示一直绘制视图
        renderMode = RENDERMODE_CONTINUOUSLY
    }

    fun getNativeRender(): MyNativeRender {
        return mNativeRender
    }

    inner class MyGLRenderer(private val myNativeRender: MyNativeRender) : Renderer {
        override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
            Log.d(TAG, "onSurfaceCreated: gl = $gl, config = $config")
            myNativeRender.native_OnSurfaceCreated()
        }

        override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
            Log.d(TAG, "onSurfaceChanged: gl = $gl, width = $width, height = $height")
            myNativeRender.native_OnSurfaceChanged(width, height)
        }

        override fun onDrawFrame(gl: GL10?) {
            Log.d(TAG, "onDrawFrame: gl = $gl")
            myNativeRender.native_OnDrawFrame()
        }

    }
}